<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useWfApi } from '@/api/wf'
import { Delete } from '@element-plus/icons-vue'

const { WorkFlowListSetStatus, WorkFlowListDel } = useWfApi()

const emit = defineEmits(['fetch', 'close'])

interface RuleForm {
  id: string | undefined
  status: number | undefined
  remark: string
}

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  id: '',
  status: undefined,
  remark: ''
})

const rules = reactive<FormRules<RuleForm>>({
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
})

/**
 * 打开窗口
 * @param id
 */
const open = (id?: string) => {
  form.id = id
  dialogVisible.value = true
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      WorkFlowListSetStatus(form).then(() => {
        dialogVisible.value = false
        ElMessage.success('流程变更成功。')
        emit('fetch')
      })
    }
  })
}

const removeWorkFlow = () => {
  ElMessageBox.confirm(`确认要删除整个流程吗？（删除后需要重新提交。）`, '删除流程提示', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      WorkFlowListDel({ id: form.id }).then(() => {
        ElMessage.success('确认删除成功')
        dialogVisible.value = false
        emit('close')
      })
    })
    .catch(() => {})
}

defineExpose({ open })
</script>

<template>
  <el-dialog v-model="dialogVisible" title="修改流程状态" width="500">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100" style="height: 180px">
      <el-form-item label="审批状态" prop="status" required>
        <el-select v-model="form.status" placeholder="请选择审批状态">
          <el-option label="已完成" :value="1" />
          <el-option label="中止" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark" required>
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="修改备注"
          rows="3"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="removeWorkFlow" :icon="Delete">清空流程</el-button>
        <el-button type="primary" @click="submitForm(formRef)"> 确认修改 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
